package com.eboss.sbs.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;

import com.dtr.zxing.activity.MyCaptureActivity;
import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.config.Config;
import com.eboss.sbs.core.FyBat;
import com.eboss.sbs.core.ZfQbAction;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.interfaces.ActionCallbackListener;
import com.eboss.sbs.model.CaculateMoneyEntity;
import com.eboss.sbs.model.UploadResultEntity;
import com.eboss.sbs.model.db.OrderDetail;
import com.eboss.sbs.model.fuyou.FyMicropayResponse;
import com.eboss.sbs.model.fuyou.FyQueryResponse;
import com.eboss.sbs.model.fuyou.FyRefundResponse;
import com.eboss.sbs.model.qianbao.ZfQbResponse;
import com.eboss.sbs.myapplication.MyApplication;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.LogUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.StringUtils;
import com.mytools.tool.utils.SystemUtil;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyDialog;
import com.wosai.upay.bean.UpayOrder;
import com.wosai.upay.bean.UpayResult;
import com.wosai.upay.common.DebugConfig;
import com.wosai.upay.common.UpayCallBack;
import com.wosai.upay.common.UpayTask;
import com.wosai.upay.http.Env;

import org.litepal.crud.DataSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PayChannelChooseActivity extends BaseActivity {

    public static String CACULATE_MONEY_ENTITY = "CACULATE_MONEY_ENTITY";

    private static final int REQUEST_FY_CAPTURE_WX = 0;
    private static final int REQUEST_FY_CAPTURE_ALY = 1;
    private static final int REQUEST_ZF_CAPTURE_QB = 2;

    private String password;
    private String couponSns;
    private int pointAmount;

    private CaculateMoneyEntity caculateMoneyEntity;
    private int pay_channel = 0;

    private UpayTask upayTask;  //sqb
    private FyBat fybat;        //fuyou
    private ZfQbAction qb;      //qianbao

    private int scanPayType;// = ScanPayType.SQB.getType();
    private String groundId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        mActivity = this;
        setContentView(R.layout.activity_pay_channel_choose);
        super.onCreate(savedInstanceState);

        scanPayType = mApp.getLoginEntity().getScanPayType();

        caculateMoneyEntity = (CaculateMoneyEntity) getIntent().getSerializableExtra(CACULATE_MONEY_ENTITY);
        password = getIntent().getStringExtra("password");
        couponSns = getIntent().getStringExtra("couponSns");
        pointAmount = getIntent().getIntExtra("pointAmount", 0);

        initView();

        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            initSqbSDK();
        }

        if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            fybat = new FyBat(this, mApp.getLoginEntity().getFyMerchantNo(), new PayResultEvent());        //fuyou init
        }

        qb = new ZfQbAction(this);

        //getData();



    }

    /**
     * 富友扫码支付成功后回调这里
     *
     * @author bxq
     */
    class PayResultEvent implements FyBat.FYPayResultEvent {
        @Override
        public void onSuccess(FyMicropayResponse data, String client_sn) {
            doSubmit(client_sn, data.getTransaction_id(), data.getMchnt_order_no());

        }

        @Override
        public void onSuccess(FyQueryResponse data, String client_sn) {
            doSubmit(client_sn, data.getTransaction_id(), data.getMchnt_order_no());
        }

        @Override
        public void onFailure(int statusCode, String error_msg, String client_sn) {
        }

        @Override
        public void onSuccess(FyRefundResponse data, String client_sn) {
        }
    }

    private void initSqbSDK() {
        upayTask = UpayTask.getInstance();
        DebugConfig.setDebug(Config.SQB_IS_DEBUG);//默认为非调试模式,如果需要调试,请设置为 true,打印和保存相关日志
        upayTask.initUpay(this, true, Env.UrlType.PRO);
    }

    private void initView() {
        setTvText(R.id.tv_title, "选择支付渠道");

        setTvText(R.id.tv_trade_money, StringUtil.getMoneyString(caculateMoneyEntity.getTradeMoney()) + "元");
        setTvText(R.id.tv_point_money, StringUtil.getMoneyString(caculateMoneyEntity.getPointCoverMoney()) + "元");
        setTvText(R.id.tv_coupon_money, StringUtil.getMoneyString(caculateMoneyEntity.getCouponCoverMoney()) + "元");
        setTvText(R.id.tv_real_money, StringUtil.getMoneyString(caculateMoneyEntity.getRealMoney()) + "元");

        int realMoney = caculateMoneyEntity.getRealMoney();
        showView(R.id.layout_channels, realMoney != 0);
        showView(R.id.layout_cash_pay, realMoney == 0);

        findViewById(R.id.layout_alipay).setOnClickListener(this);
        findViewById(R.id.layout_weixin).setOnClickListener(this);
        findViewById(R.id.layout_qb).setOnClickListener(this);
        findViewById(R.id.layout_baidu).setOnClickListener(this);
        findViewById(R.id.layout_jingdong).setOnClickListener(this);
        findViewById(R.id.layout_pay_cash).setOnClickListener(this);
        findViewById(R.id.layout_pay_card).setOnClickListener(this);
        findViewById(R.id.titleback_btn_back).setOnClickListener(this);
        findViewById(R.id.btn_cash_pay).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_alipay:
                pay_channel = EnumConsts.SqbPayChannel.ALIPAY.getType();
                if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
                    execute_sqb();
                } else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
                    execute_fuyou();
                    //toast("富友-支付宝-收款");
                }
                break;
            case R.id.layout_weixin:
                pay_channel = EnumConsts.SqbPayChannel.WEIXIN.getType();
                if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
                    execute_sqb();
                } else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
                    execute_fuyou();
                    //toast("富友-微信-收款");
                }
                break;
            case R.id.layout_qb:
                pay_channel = EnumConsts.SqbPayChannel.WALLET.getType();
                scanPayType = EnumConsts.ScanPayType.WALLET.getType();
                execute_qb();
                break;
//			case R.id.layout_baidu:
//				pay_channel = SqbPayChannel.BAIDU.getType();
//				execute();
//				break;
//			case R.id.layout_jingdong:
//				pay_channel = SqbPayChannel.JINGDONG.getType();
//				execute();
//				break;
            case R.id.titleback_btn_back:
                finish();
                break;
            case R.id.layout_pay_cash:
                Intent intent1 = new Intent(mActivity, PayCashActivity.class);
                intent1.putExtra(PayCashActivity.CACULATE_MONEY_ENTITY, caculateMoneyEntity);
                intent1.putExtra("password", password);
                intent1.putExtra("couponSns", couponSns);
                intent1.putExtra("pointAmount", pointAmount);
                startActivity(intent1);
                //finish();
                break;
            case R.id.layout_pay_card:
                Intent intent2 = new Intent(mActivity, PayCardActivity.class);
                intent2.putExtra(PayCashActivity.CACULATE_MONEY_ENTITY, caculateMoneyEntity);
                intent2.putExtra("password", password);
                intent2.putExtra("couponSns", couponSns);
                intent2.putExtra("pointAmount", pointAmount);
                startActivity(intent2);
                //finish();
                break;
            case R.id.btn_cash_pay:
                MyDialog dialog;
                MyDialog.Builder builder = new MyDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("确认交易完成？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        pay_cash_zero_submit();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                    }
                });


                dialog=builder.create();
//                dialog.setCancelable(false);
                dialog.show();

//                builder.create().show();
                break;
            default:
                break;
        }
    }

    /**
     * 积分或者优惠券抵消后，实际支付为0的情况
     */
    private void pay_cash_zero_submit() {

        final String clientOrderNo = PayChannelChooseActivity.getNewClientSn(mActivity, EnumConsts.SqbPayChannel.CASH_MEMO.getType(), scanPayType);
        long t = new Date().getTime();

        saveLocalTradeDetail_paycash_zero(t, clientOrderNo);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sid", mApp.getLoginEntity().getSid());
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            params.put("cardNo", memberCardNo);
        } else {
            params.put("cardNo", "");
        }
        if (!StringUtil.isNull(password)) {
            params.put("password", password);
        } else {
            params.put("password", "");
        }
        if (!StringUtil.isNull(couponSns)) {
            params.put("couponSns", couponSns);
        } else {
            params.put("couponSns", "");
        }

        params.put("cash", caculateMoneyEntity.getRealMoney());
        params.put("bankAmount", "");
        params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        params.put("clientOrderNo", clientOrderNo);
        //params.put("terminalNo", PayChannelChooseActivity.getActivateCodeId(this));

        //收钱吧
        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            params.put("activateCode", LocalParasUtils.getActivateCode(this));
            params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
        }
        //富友
        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            params.put("activateCode", mApp.getLoginEntity().getActivateCode());
            params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
        }

        params.put("t", t);
        params.put("transNo", "");
        params.put("authCode", "");
        params.put("pointAmount", pointAmount);
        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        params.put("serialNum", imei);
        params.put("payType", EnumConsts.SqbPayChannel.CASH_MEMO.getType());

        API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {
            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                updateOrderDetail(clientOrderNo, data);
                openConfirmDialog(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
            }

            @Override
            public void onFailure(int statusCode, String message) {
                openConfirmDialog(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({"unchecked", "rawtypes"})
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {
                };
            }
        });
    }

    /**
     * 当支付金额减去优惠金额，结果为0时，本地流水记录保存
     *
     * @param t
     * @param tradeOrderNo
     */
    private void saveLocalTradeDetail_paycash_zero(long t, String tradeOrderNo) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setTradeOrderNo(tradeOrderNo);
        orderDetail.setPayType(EnumConsts.SqbPayChannel.CASH_MEMO.getType());

        orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
        orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
        orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
        orderDetail.setMemberName(caculateMoneyEntity.getMemberName());
        //orderDetail.setPointCost(caculateMoneyEntity.getPointCoverMoney());

        int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
        int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
        String couponString = couponCoverMoney == 0 ? "" : ("优惠券抵消" + StringUtil.getMoneyString(couponCoverMoney) + "元;");
        String pointString = pointCoverMoney == 0 ? "" : ("积分抵消" + StringUtil.getMoneyString(pointCoverMoney) + "元;");

        if (!StringUtil.isNull(couponString) && !StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(pointString + couponString);
        } else if (StringUtil.isNull(couponString) && !StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(pointString);
        } else if (!StringUtil.isNull(couponString) && StringUtil.isNull(pointString)) {
            orderDetail.setBenefit(couponString);
        } else {
            orderDetail.setBenefit("");
        }

        orderDetail.setTradeTime(t);
        if (!StringUtil.isNull(password)) {
            orderDetail.setPassword(password);
        }
        if (!StringUtil.isNull(couponSns)) {
            orderDetail.setCouponSns(couponSns);
        }
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            orderDetail.setCardNo(memberCardNo);
        }


        //收钱吧
        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            orderDetail.setTerminalSn("" + LocalParasUtils.getActivateCode(mActivity));
            orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mActivity));
            orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mActivity));
            orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
        }
        //富友
        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
            orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
            orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
            orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
        }

        orderDetail.setPointAmount(pointAmount);

        orderDetail.setCash(0);
        orderDetail.setBankAmount(0);

        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        orderDetail.setSerialNum(tm.getDeviceId());
        orderDetail.save();
    }

    private void execute_sqb() {
        String code = LocalParasUtils.getActivateCode(PayChannelChooseActivity.this);
        //if(paytype==PayType.SCAN.getType()){
        pay_scan_sqb(code);
        //}
    }

    //fuyou scan pay
    private void execute_fuyou() {
        if (pay_channel == EnumConsts.SqbPayChannel.ALIPAY.getType()) {
            startActivityForResult(new Intent(mActivity, MyCaptureActivity.class), REQUEST_FY_CAPTURE_ALY);
        } else if (pay_channel == EnumConsts.SqbPayChannel.WEIXIN.getType()) {
            startActivityForResult(new Intent(mActivity, MyCaptureActivity.class), REQUEST_FY_CAPTURE_WX);
        }
    }

    //qb scan pay
    private void execute_qb(){
        startActivityForResult(new Intent(mActivity, MyCaptureActivity.class), REQUEST_ZF_CAPTURE_QB);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //富友扫码_微信
            case REQUEST_FY_CAPTURE_WX:
                String result_wx = data.getStringExtra("result");
                //Log.e("result", result_wx);
                //fybat.set
                String client_sn_1 = getNewClientSn(mActivity, pay_channel, scanPayType);
                fybat.pay(client_sn_1, result_wx, EnumConsts.FYScanChannel.PAY_FY_WX.getChannel(), caculateMoneyEntity.getRealMoney());
                break;
            //富友扫码_支付宝
            case REQUEST_FY_CAPTURE_ALY:
                String result_aly = data.getStringExtra("result");
                //Log.e("result", result_aly);
                String client_sn_2 = getNewClientSn(mActivity, pay_channel, scanPayType);
                fybat.pay(client_sn_2, result_aly, EnumConsts.FYScanChannel.PAY_FY_ALY.getChannel(), caculateMoneyEntity.getRealMoney());
                break;
            case REQUEST_ZF_CAPTURE_QB:
                String result_qb = data.getStringExtra("result");
                ZfQbPay(result_qb);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 钱包支付
     * @param result_qb
     */
    private void ZfQbPay(String result_qb) {

        if (StringUtils.isEmpty(result_qb)){
            toast("获取扫码信息为空");
            return;
        }
        int sid = MyApplication.getmInstance().getLoginEntity().getSid();
        final String orderNo = getNewClientSn(mActivity, pay_channel, scanPayType);
        final String time = StringUtils.getFormatCurTime();
        final String traceNum = StringUtils.getFormatCurTime()+StringUtils.createRandomNumStr(5);
        this.qb.qbAction(sid, orderNo, caculateMoneyEntity.getRealMoney()+"", time, traceNum, result_qb, new ActionCallbackListener<ZfQbResponse>() {
            @Override
            public void onSuccess(ZfQbResponse data) {
//                setQbPay(data, orderNo, time, traceNum);
                groundId = data.getGroupId();
                LogUtils.e("groundId", groundId);
                doSubmit(orderNo, traceNum, data.getSystemOrderNo());
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                toast(errorEvent+"#"+message);
            }
        });

    }

    /**
     * 收钱吧扫码支付
     *
     * @param code
     */
    private void pay_scan_sqb(String code) {
        UpayOrder order = new UpayOrder();
        String myOrderId = getNewClientSn(mActivity, pay_channel, scanPayType);
        order.setClient_sn(myOrderId);                //商户订单号
        order.setTotal_amount("" + caculateMoneyEntity.getRealMoney());    //交易总金额
        order.setPayway("" + pay_channel);            //支付通道
        order.setSubject(Config.SQB_SUBJECT);                    //交易subject
        order.setOperator(code);                                //操作员//这里传激活码
        order.setDescription(Config.SQB_DESCRIPTION);            //商品详情
        order.setReflect("");                                    //反射参数
        /**
         * pay 付款
         * @param order 业务订单
         * @param callBack 请求回调
         */
        upayTask.pay(order, new UpayCallBack() {
            @Override
            public void onExecuteResult(UpayResult result) {
                String resultCode = result.getResult_code();
                if (null != result && !StringUtil.isNull(resultCode) && resultCode.equals("PAY_SUCCESS")) {
                    doSubmit(result.getClient_sn(), result.getTrade_no(), result.getSn());
                }
            }
        });
    }

    /**
     * * 收钱吧/富友扫码支付成功后上传
     *
     * @param client_sn 客户端生成订单号
     * @param trade_no  交易流水号（第三方）
     * @param sn        交易机构订单号（富友/收钱吧）
     */
    private void doSubmit(final String client_sn, String trade_no, String sn) {

        long t = new Date().getTime();
        saveLocalTradeDetail(t, client_sn, trade_no, sn);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sid", mApp.getLoginEntity().getSid());
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            params.put("cardNo", memberCardNo);
        } else {
            params.put("cardNo", "");
        }
        if (!StringUtil.isNull(password)) {
            params.put("password", password);
        } else {
            params.put("password", "");
        }
        if (!StringUtil.isNull(couponSns)) {
            params.put("couponSns", couponSns);
        } else {
            params.put("couponSns", "");
        }

        params.put("cash", 0);
        params.put("bankAmount", caculateMoneyEntity.getRealMoney());
        params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
        params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
        params.put("clientOrderNo", client_sn);

        //收钱吧
        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            params.put("activateCode", LocalParasUtils.getActivateCode(this));
            params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
        }
        //富友
        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            //富友
            params.put("activateCode", mApp.getLoginEntity().getActivateCode());
            params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
        }

        //钱包
        else if (scanPayType == EnumConsts.ScanPayType.WALLET.getType()){

            if (EnumConsts.ScanPayType.SQB.getType() == mApp.getLoginEntity().getScanPayType()){
                params.put("activateCode", LocalParasUtils.getActivateCode(this));
                params.put("merchantNo", StringUtil.isNull(groundId) ? "":groundId);

            }else if (EnumConsts.ScanPayType.FUYOU.getType() == mApp.getLoginEntity().getScanPayType()){
                params.put("activateCode", mApp.getLoginEntity().getActivateCode());
                params.put("merchantNo", StringUtil.isNull(groundId) ? "":groundId);
            }
        }

        params.put("pointAmount", pointAmount);
        params.put("t", t);

        params.put("transNo", trade_no);    //交易流水号（第三方）
        params.put("authCode", sn);            //交易机构订单号（收钱吧）

        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        params.put("serialNum", imei);
        params.put("payType", pay_channel);

        API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {

            @Override
            public void onSuccess(int statusCode, UploadResultEntity data) {
                updateOrderDetail(client_sn, data);
                openConfirmDialog(pay_channel);
            }

            @Override
            public void onFailure(int statusCode, String message) {
                openConfirmDialog(pay_channel);
                super.onFailure(statusCode, message);
            }

            @SuppressWarnings({"unchecked", "rawtypes"})
            @Override
            public TypeToken getTypeToken() {
                return new TypeToken<UploadResultEntity>() {
                };
            }
        });
    }

    /**
     * 收钱吧扫码支付成功并上传服务器流水后，用返回的内容更新本地保存的交易记录（主要是更新交易返回的积分和优惠券二维码）
     */
    private void updateOrderDetail(String clientOrderNo, UploadResultEntity data) {
        ContentValues cv = new ContentValues();
        String point_url = data.getPoint_url();
        String coupon_url = data.getCoupon();
        cv.put("point_url", StringUtil.isNull(point_url) ? "" : point_url);
        cv.put("coupon_url", StringUtil.isNull(coupon_url) ? "" : coupon_url);
        int point = data.getPoint();
        int pointCurrent = data.getPointCurrent();
        cv.put("point", point);
        cv.put("pointCurrent", pointCurrent);

        DataSupport.updateAll(OrderDetail.class, cv, "tradeOrderNo = ?", clientOrderNo);
    }

    private void saveLocalTradeDetail(long t, String tradeOrderNo, String trade_no, String sn) {

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setTradeOrderNo(tradeOrderNo);
        orderDetail.setPayType(pay_channel);
        orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
        orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
        orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
        orderDetail.setMemberName(caculateMoneyEntity.getMemberName());

        //收钱吧
        if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            orderDetail.setTerminalSn(LocalParasUtils.getActivateCode(mActivity));
            orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mActivity));
            orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mActivity));
            orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
        }
        //富友
        else if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
            orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
            orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
            orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
        }

        //钱包
        else if (scanPayType == EnumConsts.ScanPayType.WALLET.getType()){
            orderDetail.setTerminalSn(StringUtil.isNull(groundId) ? "":groundId);
            orderDetail.setMerchantNo(StringUtil.isNull(groundId) ? "":groundId);
            if (EnumConsts.ScanPayType.SQB.getType() == mApp.getLoginEntity().getScanPayType()){
                orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mActivity));
                orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
            }else if (EnumConsts.ScanPayType.FUYOU.getType() == mApp.getLoginEntity().getScanPayType()){
                orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
                orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
            }

        }


        int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
        int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
        String couponString = couponCoverMoney == 0 ? "" : ("优惠券抵消" + StringUtil.getMoneyString(couponCoverMoney) + "元;");
        String pointString = pointCoverMoney == 0 ? "" : ("积分抵消" + StringUtil.getMoneyString(pointCoverMoney) + "元;");
        if (!StringUtil.isNull(couponString) || !StringUtil.isNull(pointString))
            orderDetail.setBenefit(pointString + couponString);

        orderDetail.setTradeTime(t);
        if (!StringUtil.isNull(password)) {
            orderDetail.setPassword(password);
        }
        if (!StringUtil.isNull(couponSns)) {
            orderDetail.setCouponSns(couponSns);
        }
        String memberCardNo = caculateMoneyEntity.getMemberCardNo();
        if (!StringUtil.isNull(memberCardNo)) {
            orderDetail.setCardNo(memberCardNo);
        }

        orderDetail.setTransNo(trade_no);
        orderDetail.setAuthCode(sn);

        orderDetail.setPointAmount(pointAmount);
        orderDetail.setSerialNum(SystemUtil.getImsi(mActivity));
        ;

        orderDetail.setCash(0);
        orderDetail.setBankAmount(caculateMoneyEntity.getRealMoney());

        orderDetail.save();
    }

    private void openConfirmDialog(int channel) {
        MyDialog.Builder builder = new MyDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(EnumConsts.SqbPayChannel.getByType(channel).getName() + "收款成功！");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startActivity(new Intent(mActivity, PayMoneyInputActivity.class));

                Intent intent = new Intent(PayMoneyInputActivity.RECEIVER_CLEAN_DATA_TAG);
                intent.putExtra(PayMoneyInputActivity.NOTIFY_CODE_TAG, PayMoneyInputActivity.CLEAN_DATA);
                sendBroadcast(intent);
                finish();
            }
        });
        builder.create().show();
    }

    //自己生成订单号
    public static String getNewClientSn(Context context, int payType_in, int scanPayType) {
        String orderNo = "";
        String device = "1";    //1:手机  2:Pos机
        String payType = "" + payType_in;
        String timestamp = TimeUtil.getCurrentDateString("yyyyMMddHHmmss");
        String randomNum = StringUtil.createRandomStr("0123456789", 3);
        String activateCode = "";
        if (scanPayType == EnumConsts.ScanPayType.FUYOU.getType()) {
            activateCode = MyApplication.getmInstance().getLoginEntity().getActivateCode();
        } else if (scanPayType == EnumConsts.ScanPayType.SQB.getType()) {
            activateCode = LocalParasUtils.getActivateCode(context);
        }
        orderNo = device + payType + timestamp + randomNum + activateCode;
        return orderNo;
    }

}
